import React, { Component, Fragment } from 'react'
import { inject, observer } from 'mobx-react/index'
import { Card, Button, Modal, Table, Spin, message, Form, InputNumber } from 'antd'

import { address } from '@/Utils/apiConfig'
import { limitDecimals } from '@/Utils/common'
import getData from '@/Utils/fecth'
import Empty from '@/pages/Dashboard/common/Empty/index'
import { STATUSCLASS } from '@/Utils/CONST.js'
import Event from '@/Utils/Event'
import { PEERNODEJOINCHANNEL, CREATECHANNEL } from '@/Utils/socketName'
import { checkPermission } from '@/components/AuthComponent/utils'

import './index.less'

const { leagueManagement: { getChannelList }} = address
const STATUS = {
  'CREATING': '创建中',
  'SUCCESS': '创建成功',
  'FAILED': '创建失败',
}

@inject('SocketModel')
@observer
class Channel extends Component {
  columns = [
    {
      title: '通道名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '通道ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '组织数量',
      dataIndex: 'orgNum',
      key: 'orgNum',
    },
    {
      title: '节点数量',
      dataIndex: 'nodeNum',
      key: 'nodeNum',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (text) => <span className={STATUSCLASS[text]}>{STATUS[text]}</span>,
    },
    {
      title: '操作',
      dataIndex: 'operate',
      key: 'operate',
      render: (text, record) => (
        <Fragment>
          {
            checkPermission('fabric-channel-apply') && !record.isJoin &&
            <span
              style={{ paddingLeft: 0 }}
              className="common-operation"
              onClick={() => this.applyJoin(record)}
            >
              申请加入
            </span>
          }
          {
            checkPermission('fabric-channel-org') && !!record.isJoin &&
            <span
              style={{ paddingLeft: 0 }}
              className="common-operation"
              onClick={() => this.toOrganization(record)}
            >
              组织管理
            </span>
          }
          {
            checkPermission('fabric-channel-config') &&
            <span
              style={{ paddingLeft: 0 }}
              className="common-operation"
              onClick={() => this.editChannel(record)}
            >
            修改通道配置
            </span>
          }
          {/* <Popover
              placement="bottom"
              content={
                <div>
                  {
                    !leagueInfo.isGuomi && <Fragment>
                      <p className="cursor hover" onClick={() => this.downloadSdk('node', record.id)}>node配置文件</p>
                      <p className="cursor hover" onClick={() => this.downloadSdk('java', record.id)}>java配置文件</p>
                    </Fragment>
                  }
                  <p className="cursor hover" onClick={() => this.downloadSdk('golang', record.id)}>go配置文件</p>
                </div>
              }
            >
              <span className="common-operation ml8">下载SDK配置文件</span>
            </Popover> */}
        </Fragment>
      ),
    },
  ]

  constructor(props) {
    super(props)
    this.state = {
      consortiumId: props.match.params.id,
      name: props.match.params.name,
      list: [],
      totalNum: 0,
      page: 1,
      pageSize: 10,
      loading: true,
      searchValue: '',
      visible: false,
    }
    this.totalData = []
    this.handleRecord = {}
  }

  componentDidMount() {
    this.getChannelList()
    Event.on(CREATECHANNEL, this.getChannelList) // 创建通道
    Event.on(PEERNODEJOINCHANNEL, this.getChannelList) // peer节点加入通道
  }

  componentWillUnmount() {
    Event.off(CREATECHANNEL, this.getChannelList)
    Event.off(PEERNODEJOINCHANNEL, this.getChannelList)
  }

  editChannel = (record) => {
    this.handleRecord = record
    this.setState({
      visible: true,
    })
  }

  toOrganization = (record) => {
    const { consortiumId, name } = this.state
    this.props.history.push({
      pathname: `/dashboard/fabric/leagueInfo/${consortiumId}/${name}/channelOrg/${record.id}/${record.name}`,
    })
  }

  applyJoin = (record) => {
    const { consortiumId, name } = this.state
    this.props.history.push({
      pathname: `/dashboard/fabric/leagueInfo/${consortiumId}/${name}/joinChannel/${record.id}/${record.name}/APPLY`,
    })
  }

  // 获取组织列表
  getChannelList = async() => {
    const { consortiumId, page, pageSize } = this.state
    let list = null
    getData().get(getChannelList.format({ consortiumId: consortiumId, pageNum: page, pageSize })).then((res = {}) => {
      if (res.status === 200) {
        list = res.data.channels
        this.setState({
          list,
          totalNum: res.data.totalNum,
          loading: false,
        })
        this.totalData = list
      }
    })
  }

  createChannel = () => {
    const { consortiumId, name } = this.state
    this.props.history.push({
      pathname: `/dashboard/fabric/leagueInfo/${consortiumId}/${name}/createChannel`,
    })
  }

  handleSearch = () => {
    const value = this.state.searchValue.trim()
    if (value) {
      const dataList = this.totalData
      const newList = dataList.filter(item => (item.id.indexOf(value) >= 0 || item.name.indexOf(value) >= 0))
      this.setState({
        list: newList,
      })
    } else {
      this.setState({
        list: this.totalData,
      })
    }
  }

  changeTable = (pagination) => {
    const { current, pageSize } = pagination
    this.setState({
      page: current,
      pageSize,
    }, () => {
      this.getChannelList()
    })
  };

  // 修改网通道配置
  edit = () => {
    this.editForm && this.editForm.validateFields().then(async(values) => {
      let params = {}
      Object.keys(values).forEach(key => {
        const value = values[key]
        if (value || value === 0) {
          params[key] = value
        }
      })
      if (Object.keys(params).length > 0) {
        const { id } = this.props.match.params
        const { status } = await getData().post(address.leagueManagement.updateChannel, {
          channelName: this.handleRecord.name,
          consortiumId: id,
          ...params,
          batch_timeout: `${params.batch_timeout}s`,
        })
        if (status === 200) {
          this.getChannelList()
          message.success('操作成功！')
          this.setState({
            visible: false,
          })
        }
      } else {
        this.setState({
          visible: false,
        })
      }
    })
  }

  render() {
    const { list, pageSize, page, totalNum, visible, loading } = this.state

    return (
      <Card className="channel-box common">
        <div className="mb24 search-operate">
          {
            checkPermission('fabric-channel-create') &&
            <Button
              type="primary"
              onClick={this.createChannel}
              style={{ marginBottom: 20 }}>
            创建通道
            </Button>
          }
          <div className="common-search" ref={elm => { this.elm = elm }}>
            <input ref={b => this.input = b}
              className="search-input"
              placeholder="请输入通道名/通道ID"
              type="text"
              onKeyDown={(event) => {
                event.keyCode === 13 && this.handleSearch()
              }}
              value={this.state.searchValue}
              autoComplete="off"
              onChange={(e) => this.setState({ searchValue: e.target.value })}
            />
            <div className="search-btn">
              <img src={require('@/images/org/search.svg')} alt="" onClick={this.handleSearch} />
            </div>
          </div>
        </div>
        <Spin spinning={loading}>
          <Table
            columns={this.columns}
            dataSource={list}
            rowKey={record => record.id}
            pagination={{
              pageSize,
              current: page,
              pageSizeOptions: ['5', '10', '20', '50'],
              simple: false,
              showQuickJumper: true,
              showSizeChanger: true,
              total: totalNum,
            }}
            className={list.length ? '' : 'empty-list'}
            onChange={this.changeTable}
            locale={{
              emptyText: <div />,
            }}
          />
          {!list.length && <Empty />}
        </Spin>
        <Modal
          centered
          destroyOnClose
          getContainer={() => this.elm}
          title={'修改通道配置'}
          onCancel={() => this.setState({ visible: false })}
          visible={visible}
          onOk={this.edit}
          className="network-edit"
        >
          <Form
            ref={ref => { this.editForm = ref }}
            {...{
              labelCol: { span: 8 },
              wrapperCol: { span: 16 },
            }}
          >
            <Form.Item
              label="区块打包超时时间："
              name="batch_timeout"
              initialValue={this.handleRecord.batch_timeout ? parseInt(this.handleRecord.batch_timeout, 10) : null}
              rules={[
                {
                  required: true,
                  message: '请输入区块打包超时时间',
                },
              ]}
            >
              <InputNumber
                style={{ width: '180px' }}
                placeholder="请输入区块打包超时时间"
                min={0}
                formatter={value => value ? `${value}s` : ''}
                parser={value => value.replace('s', '')}
              />
            </Form.Item>
            <Form.Item
              label="区块打包交易数："
              name="batch_message_count"
              initialValue={this.handleRecord.batch_message_count || null}
              rules={[
                {
                  required: true,
                  message: '请输入区块打包交易数',
                },
              ]}
            >
              <InputNumber
                style={{ width: '180px' }}
                placeholder="请输入区块打包交易数"
                formatter={limitDecimals(0)}
                parser={limitDecimals(0)}
                min={0} />
            </Form.Item>
            <Form.Item
              label="区块打包字节数："
              name="batch_max_bytes"
              initialValue={this.handleRecord.batch_max_bytes ? parseInt(this.handleRecord.batch_max_bytes, 10) : null}
              rules={[
                {
                  required: true,
                  message: '请输入区块打包字节数',
                },
              ]}
            >
              <InputNumber
                style={{ width: '180px' }}
                formatter={value => value ? `${value}KB` : ''}
                parser={value => value.replace('KB', '')}
                placeholder="请输入区块打包字节数"
                min={0} />
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    )
  }
}
export default Channel
